<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\ocean;

use app\command\BaseWork;
use app\enum\ConfigEnum;
use app\enum\OceanEnum;
use app\service\fetch\OceanFetchService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class CarouselWork extends BaseWork
{
    public const REDIS_TASK_KEY = ConfigEnum::CACHE_CONFIG[OceanEnum::LIST_CONFIG_KEY]['mongo_video_tag'];

    protected function configure()
    {
        // 指令配置
        $this->setName('oe_carousel_work');
        // 设置参数
        $this->setDescription('拉取图文素材增量列表');

        // 设置参数
        $this->addArgument('advertiser_id', null, '账户id')
            ->setHelp('php think oe_carousel_work [advertiser_id]');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $this->getOutputMessage('拉取图文素材增量列表开始');
        $redis = Cache::store('redis')->handler();
        $st = time() + 5 * 60;
        while (time() < $st) {
            $advertiserId = $redis->lPop(self::REDIS_TASK_KEY);
            if (! $advertiserId) {
                usleep(500000);
                continue;
            }
            $this->getOutputMessage('拉取图文素材增量列表[' . $advertiserId . ']开始');
            try {
                $res = OceanFetchService::fetchCarouselList($advertiserId);
                if (! $res) {
                    $redis->rPush(self::REDIS_TASK_KEY, $advertiserId);
                    $this->getOutputMessage('拉取图文素材增量列表[' . $advertiserId . ']失败:' . OceanFetchService::getError(0));
                }
            } catch (\Exception $e) {
                $this->getOutputMessage('拉取图文素材增量列表[' . $advertiserId . ']失败:' . $e->getMessage());
            }
            $this->getOutputMessage('拉取图文素材增量列表[' . $advertiserId . ']结束');
        }
        $this->getOutputMessage('拉取视频增量列表结束');
    }

}
